package com.wzh.glsc.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.constant.ProductConstant;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;
import com.wzh.glsc.product.dao.AttrAttrgroupRelationDao;
import com.wzh.glsc.product.dao.AttrDao;
import com.wzh.glsc.product.dao.AttrGroupDao;
import com.wzh.glsc.product.dao.CategoryDao;
import com.wzh.glsc.product.entity.AttrAttrgroupRelationEntity;
import com.wzh.glsc.product.entity.AttrEntity;
import com.wzh.glsc.product.entity.AttrGroupEntity;
import com.wzh.glsc.product.entity.CategoryEntity;
import com.wzh.glsc.product.service.AttrService;
import com.wzh.glsc.product.service.CategoryService;
import com.wzh.glsc.product.vo.AttrRespVo;
import com.wzh.glsc.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private CategoryDao categoryDao;
    @Resource
    private CategoryService categoryService;
    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Resource
    private AttrGroupDao attrGroupDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //将(源对象,所需复制的对象);
        //将源数据复制给另一个对象
        // 需要两个对象所复制的字段一一相同,对应
        BeanUtils.copyProperties(attr, attrEntity);
        baseMapper.insert(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode()) {
            if (attr.getAttrGroupId() != null && attr.getAttrGroupId() != 0) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public PageUtils queryBaseListPage(Map<String, Object> params, Long catelogId, String attrType) {
        //获取map中的查询字符 key
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        //key不为空则进行模糊查询
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id ", key).or().like("attr_name", key);
            });
        }
        if (StringUtils.isNotEmpty(attrType)) {
            queryWrapper.eq("attr_type", attrType.equalsIgnoreCase("sale") ? ProductConstant.ATTR_TYPE_SALE.getCode() : ProductConstant.ATTR_TYPE_BASE.getCode());
        }
        //执行查询
        IPage iPage = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        //分页聚合
        PageUtils pageUtils = new PageUtils(iPage);
        //获取到查询的属性数据集合
        List<AttrEntity> attrEntityList = iPage.getRecords();
        //循环 属性集合 查出每条数据的 目录名 和 分组名,并封装成AttrRespVo对象
        List<AttrRespVo> attrRespVoList = attrEntityList.stream().map((tempObj) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            //复制 属性对象 到 属性数据传输对象attrRespVo
            BeanUtils.copyProperties(tempObj, attrRespVo);
            //根据属性对象的所属目录id查出目录对象
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id", tempObj.getCatelogId()));
            //目录对象不为空就把目录句添加 到attrRespVo对象中
            if (ObjectUtils.isNotEmpty(categoryEntity)) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            if (attrType.equalsIgnoreCase("base")) {
                //根据 属性对象 的 属性id 在 属性-分组关系表 中查出 属性-分组对象
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", tempObj.getAttrId()));
                //属性-分组对象 不为空则 属性-分组对象 的所属 目录id 查出 目录对象
                if (ObjectUtils.isNotEmpty(attrAttrgroupRelationEntity)) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    //目录对象 不为空 则将目录名放入attrRespVo中
                    if (ObjectUtils.isNotEmpty(attrGroupEntity)) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            return attrRespVo;
            //用collect 聚合成List
        }).collect(Collectors.toList());
        //把聚合分页对象中的集合替换成查出来的新集合attrRespVoList
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttr(Long attrId) {
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        AttrRespVo attrVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrVo);
        if (attrEntity.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (ObjectUtils.isNotEmpty(attrAttrgroupRelationEntity)) {
                attrVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (ObjectUtils.isNotEmpty(attrGroupEntity)) {
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        Long[] catagoryPath = categoryService.getCatelogPathBycatId(attrEntity.getCatelogId());
        if (ObjectUtils.isNotEmpty(catagoryPath)) {
            attrVo.setCatalogPath(catagoryPath);
        }
        return attrVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrRespVo attrRespVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrRespVo, attrEntity);
        baseMapper.updateById(attrEntity);
        if (attrRespVo.getAttrType() == ProductConstant.ATTR_TYPE_BASE.getCode()) {
            if (attrRespVo.getAttrGroupId() != null && attrRespVo.getAttrGroupId() != 0) {
                AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelation.setAttrId(attrRespVo.getAttrId());
                attrAttrgroupRelation.setAttrGroupId(attrRespVo.getAttrGroupId());
                Integer count = attrAttrgroupRelationDao.selectCount(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId())
                );
                if (count > 0) {
                    attrAttrgroupRelationDao.update(attrAttrgroupRelation, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId()));
                } else {
                    attrAttrgroupRelationDao.insert(attrAttrgroupRelation);
                }
            }

        }
    }

    @Override
    public PageUtils noattrRelation(Map<String, Object> params, Long attrGroupId) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        String key = (String) params.get("key");
        //查出分组同种类下没有被分配分组的基本属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", attrGroupEntity.getCatelogId())
                .eq("attr_type", ProductConstant.ATTR_TYPE_BASE.getCode())
                .notInSql("attr_id", "select attr_id from pms_attr_attrgroup_relation");
        //支持分页和模糊查询
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((tempSqlObj) -> {
                tempSqlObj.eq("attr_id", key).or()
                        .like("attr_name ", key).or()
                        .like("icon", key).or()
                        .like("value_select", key);
            });
        }
        IPage<AttrEntity> iPage = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(iPage);
    }

    @Override
    public List<AttrEntity> getRelationAttrByAttrGroupId(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrEntity>  attrEntityList=attrAttrgroupRelationEntityList.stream().map((obj) -> {
            return baseMapper.selectById(obj.getAttrId());
        }).collect(Collectors.toList());
        return attrEntityList;
    }

    @Override
    public List<Long> getSearchAttrIdByAttrs(List<Long> attrIdList) {
        return baseMapper.getSearchAttrIdByAttrs(attrIdList,ProductConstant.ATTR_SEARCH_YES.getCode());
    }

}